"""
序列化器的作用
    -序列化
    -反序列化

定义序列化器：
1、定义类，继承自 Serializer
2、和模型类，字段名称一样
3、和模型类，字段类型一样
4、和模型类，字段选项一样
"""

from rest_framework import serializers
from apps.drf_test_0Django原始restful.models import BookinfoModels



def check_bpub_datae(value):
    if value.year < 2018:
        raise serializers.ValidationError("书籍年份不能小于2018")

class BookInfSerizlizer(serializers.Serializer):
    """
    书籍序列化器
    """
    id = serializers.IntegerField(label='id',read_only=True)
    btitle = serializers.CharField(label='名称',max_length=20)
    bpub_date = serializers.DateField(label='发布日期',validators=[check_bpub_datae])
    bread = serializers.IntegerField(label='阅读量',default=0)
    bcomment = serializers.IntegerField(label='评论量',default=0)
    is_delete = serializers.BooleanField(label='逻辑删除',default=False)


    # 单字段校验
    def validate_btitle(self, value):
        print(value)
        if "数学" not in value:
            raise serializers.ValidationError('书籍未包含数学')
        return value

    # 多字段校验
    def validate(self, attrs):
        bread = attrs['bread']
        bcomment = attrs['bcomment']
        if bread < bcomment:
            raise serializers.ValidationError("评论量不能大于阅读量")
        return attrs

    # 重写create方法，实现数据入库
    def create(self, validated_data):
        return BookinfoModels.objects.create(**validated_data)

    # 重写update方法，实现更新入库
    def update(self, instance, validated_data):
        instance.btitle = validated_data['btitle']
        instance.bpub_date = validated_data['bpub_date']
        instance.bread = validated_data['bread']
        instance.bcomment = validated_data['bcomment']
        instance.save()
        return instance






    # 1、关联英雄，主键,在一方查多方需要加上many=True，返回书籍id
    # heroinfomodels_set = serializers.PrimaryKeyRelatedField(read_only=True,many=True) #模型类的小写_set
    # 2、关联英雄，主键，返回具体书名
    # heroinfomodels_set = serializers.StringRelatedField(read_only=True,many=True) #模型类的小写_set


class HeroSerizlizer(serializers.Serializer):
    """
    英雄序列化器
    """
    GENDER_CHOICES = (
        (0,'male'),
        (1,'female'),
    )
    id = serializers.IntegerField(label='id',read_only=True)
    hname = serializers.CharField(max_length=20,label='名称')
    hgender = serializers.ChoiceField(choices=GENDER_CHOICES,label='性别',required=False)
    hcomment = serializers.CharField(max_length=200,allow_null=True,label='描述信息',required=False)

    # 1、关联书籍,外键。read_only=True表示只读，或者设置queryset = BookInfoModels.objects.all()
    # hbook = serializers.PrimaryKeyRelatedField(read_only=True)
    # 2、关联书籍，使用模型类__str__方法返回值
    # hbook = serializers.StringRelatedField(read_only=True)
    # 3、关联书籍，返回书籍的全部字段
    hbook = BookInfSerizlizer()